﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace TbDataSync
{
    public partial class Program
    {

        /// <summary>
        /// 同步时序数据
        /// </summary>
        /// <param name="oldDeviceId"></param>
        /// <param name="newDeviceId"></param>
        public static void TransferTimeseries(string oldDeviceId, string newDeviceId)
        {
            var token = GetToken(newDeviceId, new_client);
            var url = urls["time_list"].Replace("%deviceId%", oldDeviceId);
            var key_list = old_client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
            var list = JsonConvert.DeserializeObject<List<string>>(key_list);
            var keys = string.Join(',', list);
            var seriesUrl = urls["get_timeseries"]
                .Replace("%deviceId%", oldDeviceId)
                .Replace("%keys%", keys)
                .Replace("%startTs%", $"{startTs}")
                .Replace("%endTs%", $"{endTs}")
                ;
            var series = old_client.GetAsync(seriesUrl).Result.Content.ReadAsStringAsync().Result;
            Log.Info($"源设备时序数据已获取 设备ID:{oldDeviceId}");
            var j = JsonConvert.DeserializeObject<JObject>(series);
            if (j != null)
            {
                //遍历每一个键，发送到新设备
                foreach (var item in list)
                {
                    if (j[item] != null)
                    {
                        var tsitems = JArray.Parse(j[item].ToString());
                        foreach (var tsitem in tsitems)
                        {
                            var t = JObject.Parse(tsitem.ToString());

                            double r_l = 0;
                            var tbody = "";
                            var f = t["value"].ToString();
                            if (double.TryParse(f, out r_l) || f.StartsWith("{"))
                            {
                                tbody += $"{t["value"]}";
                            }
                            else
                            {
                                tbody += $"\"{t["value"]}\"";
                            }

                            var body = $"{{ \"ts\":{long.Parse(t["ts"].ToString())},\"values\":{{ \"{item}\":{tbody} }} }}";
                            var payload = new StringContent(body, Encoding.UTF8, "application/json");
                            var purl = urls["post_timeseries"].Replace("%token%", token);
                            var resp = new_client.PostAsync(purl, payload).Result;
                        }
                    }
                }
            }
            Log.Info($"目标设备时序数据已推送 设备ID:{newDeviceId}");
            Wait();
        }
    }
}
